package com.lvbaoins.creditapp.annotaton.support;

import com.lvbaoins.creditapp.annotaton.LoginUser;
import com.lvbaoins.creditapp.util.UserTokenManager;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.logging.Logger;


public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    Logger logger = Logger.getLogger("filter");
    public static final String LOGIN_TOKEN_KEY = "X-lvbaoins-Token";

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Integer.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        String token = nativeWebRequest.getHeader(LOGIN_TOKEN_KEY);
        if (token == null || token.isEmpty()) {
            return null;
        }
        logger.info("[方法解析器]-获取token中的userId,token:" + token);
        return UserTokenManager.getUserId(token);
    }
}
